package com.example.demolinux.controller;

import com.example.demolinux.entity.User;
import com.example.demolinux.service.UserService;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    // 查询所有用户
    @GetMapping("/list")
    public List<User> listUsers() {
        return userService.getAllUsers();
    }

    // 根据ID查询用户
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return userService.getUserById(id);
    }

    // 添加用户
    @PostMapping("/add")
    public String addUser(@RequestBody User user) {
        int result = userService.addUser(user);
        return result > 0 ? "添加成功" : "添加失败";
    }

    // 更新用户
    @PutMapping("/update")
    public String updateUser(@RequestBody User user) {
        int result = userService.updateUser(user);
        return result > 0 ? "更新成功" : "更新失败";
    }

    // 删除用户
    @DeleteMapping("/{id}")
    public String deleteUser(@PathVariable Long id) {
        int result = userService.deleteUser(id);
        return result > 0 ? "删除成功" : "删除失败";
    }

    // 测试事务成功场景
    @GetMapping("/test-success")
    public String testSuccess() {
        try {
            User user1 = new User("张三", 25, "zhangsan@example.com");
            User user2 = new User("李四", 30, "lisi@example.com");
            userService.addTwoUsers(user1, user2);
            return "成功：添加了两个用户（事务提交）";
        } catch (Exception e) {
            return "失败：" + e.getMessage();
        }
    }

    // 测试事务回滚场景
    @GetMapping("/test-rollback")
    public String testRollback() {
        try {
            User user1 = new User("王五", 28, "wangwu@example.com");
            User user2 = new User("赵六", -1, "zhaoliu@example.com");
            userService.addTwoUsers(user1, user2);
            return "成功";
        } catch (Exception e) {
            return "失败：" + e.getMessage() + "（事务已回滚，两个用户都未保存）";
        }
    }

    // 清空所有用户
    @DeleteMapping("/clear")
    public String clearUsers() {
        int result = userService.deleteAll();
        return "已清空 " + result + " 个用户";
    }
}

